package com.codi.bus.core.service.impl;

import com.codi.base.config.ConfigurationMgr;
import com.codi.base.util.PropertiesUtil;
import com.codi.base.util.StringUtil;
import com.codi.bus.constant.GlobalConstant;
import com.codi.bus.core.dao.SMSTemplateDao;
import com.codi.bus.core.dao.SendMessageDao;
import com.codi.bus.core.domain.SMSTemplate;
import com.codi.bus.core.domain.SendMessage;
import com.codi.bus.core.resultModel.SMSSendResult;
import com.codi.bus.core.service.SMSSimpleService;
import com.codi.bus.core.service.model.SMSParameter;
import com.codi.bus.util.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 简化短信发送
 *
 * @author shi.pengyan
 * @version 1.0 2017-09-04 16:43
 * @since 1.0
 */
@Slf4j
@Service
@Transactional
public class SMSSimpleServiceImpl implements SMSSimpleService {

    protected Map<String, String> smsMap = PropertiesUtil.doGetProperties("sms.properties");

    @Autowired
    private SMSTemplateDao smsTemplateDao;

    @Autowired
    private SendMessageDao sendMessageDao;

    private String smsUrl;

    @Override
    public SMSSendResult send(String mobile, String smsTemplateCode, List<SMSParameter> params) {

        return send0(mobile, smsTemplateCode, params);
    }

    @Override
    @Async
    public SMSSendResult sendAsync(String mobile, String smsTemplateCode, List<SMSParameter> params) {
        return send0(mobile, smsTemplateCode, params);
    }

    @Override
    @Async
    public SMSSendResult sendAsync(String mobile, String smsTemplateCode) {
        log.debug("begin to send sms async...");

        return send0(mobile, smsTemplateCode, null);
    }

    @Override
    @Async
    public SMSSendResult sendAsync(String mobile, String smsTemplateCode, String key, String value) {
        log.debug("begin to send sms async...");

        List<SMSParameter> params = new ArrayList<>(1);

        SMSParameter p = new SMSParameter();
        p.setKey(key);
        p.setValue(value);

        params.add(p);

        return send0(mobile, smsTemplateCode, params);
    }

    /**
     * 发送自拟短信
     *
     * @param phone   手机号码
     * @param message 短信内容
     * @param funCode 短信代码
     * @return
     */
    @Override
    public String sendMessage(String phone, String message, String funCode) {
        ConfigurationMgr configMgr = ConfigurationMgr.getInstance();
        smsUrl = configMgr.getString("codi.contactus.sms.url");
        String url = smsUrl + GlobalConstant.SMS_SEND_SIMPLE;
        Map<String, String> smsMap = new HashMap<>();
        smsMap.put("phoneNum", phone);
        smsMap.put("messageText", message);
        smsMap.put("fun", funCode);
        smsMap.put("templateCode", "无");
        return HttpClientUtil.sendPost(url, smsMap, null);
    }

    private SMSSendResult send0(String mobile, String smsTemplateCode, List<SMSParameter> params) {
        // 查找Template
        SMSTemplate template = smsTemplateDao.getEntityByTemplateCode(smsTemplateCode);
        if (template == null || StringUtil.isEmpty(template.getTemplateContent())) {
            throw new RuntimeException("短信模板不存在，请检查是否已配置短信模板" + smsTemplateCode);
        }

        String msg = params == null ? template.getTemplateContent() : buildSMSMessage(template.getTemplateContent(), params);

        storeMessage(mobile, msg, template.getSmsType());


        SMSSendResult result = new SMSSendResult();
        result.setSuccess(true);

        return result;
    }


    private void storeMessage(String mobile, String message, Integer smsType) {
        // 将数据保存到数据库
        SendMessage msg = new SendMessage();
        msg.setMobile(mobile);
        msg.setContent(message);
        String channel = GlobalConstant.SMS_CHANNEL_DEFAULT;
        if (smsMap.containsKey(GlobalConstant.SMS_PROPERTY_CHANNEL)) {
            channel = smsMap.get(GlobalConstant.SMS_PROPERTY_CHANNEL);
        }
        msg.setChannel(channel);
        //验证码
        msg.setType(smsType);
        //发送计划-立即发送
        msg.setSendPlan(GlobalConstant.SMS_PLAN_INSTANT);
        //发送状态-发送中
        msg.setSendStatus(GlobalConstant.SMS_STATUS_SENDING);
        msg.setCreateDate(new Date());
        msg.setIsValid(true);
        sendMessageDao.add(msg);
    }


    private final String buildSMSMessage(String template, List<SMSParameter> params) {
        for (SMSParameter param : params) {
            template = template.replaceAll(param.getKey(), param.getValue());
        }
        return template;
    }
}
